package com.brother.realtime;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import org.apache.log4j.Logger;

import com.brother.database.DataBase;
import com.brother.model.Signal;
import com.brother.service.RealDataService;

public class DataReceiverServer {
private Logger log = Logger.getLogger(this.getClass());
private boolean isStopped = false;	

private ServerSocket serverSocket;

private Thread t;
private ServerSocketChannel socketChannel;

public void startListener(String port){
	
	if(log.isDebugEnabled()){
		log.debug("Starting to initialize the geo data.");
		
		RealDataService rs = new RealDataService();
		rs.updateAllLastDataSignal(Signal.na);
		
		log.debug("Starting to initialize the geo data.");
	}
	
	if(log.isDebugEnabled())
		log.debug("starting the DataReceiverServer....");
	try {
		
		//this.serverSocket = new ServerSocket(Integer.parseInt(port), 250);
		this.socketChannel = ServerSocketChannel.open();//this.serverSocket.getChannel();
		this.serverSocket = this.socketChannel.socket();
		serverSocket.bind(new InetSocketAddress(Integer.parseInt(port)));
	} catch (IOException e) {
		log.equals(e);
	}
	
	t = new Thread(){
		public void run(){
			while(isStopped == false){
				if(serverSocket == null){
					break;
				}
				try {
					SocketChannel socket = socketChannel.accept();
					if(socket == null){
						log.debug("null");
						continue;
					}
					if(log.isInfoEnabled())
						log.info("client "+socket.socket().getRemoteSocketAddress()+" has connected to the server!");
					socket.configureBlocking(false); // 处于异步工作状态
					RealTimeDataProcessor processor = new RealTimeDataProcessor(socket);
					Thread pt = new Thread(processor);
					pt.setPriority(Thread.MIN_PRIORITY);
					pt.start();
					ProcessorPool.getInstance().addProcessor(processor);
				} catch (Exception e) {
					log.equals(e);
				}
			}
			if(log.isDebugEnabled())
				log.debug("the realtime data receiver server is stopped.");
		}
	};
	t.start();
	
	MileageUpdator.getInstance().start();
	DataBase.closeThreadConnection();
}

public void destroy(){
	if(log.isDebugEnabled())
		log.debug("stopping the realtime data receiver server....");
	isStopped = true;
	ProcessorPool.getInstance().stopAll();
	
	try {
		this.serverSocket.close();
	} catch (IOException e1) {
		log.error(e1);
	}
	
	
	try {
		this.serverSocket.close();
	} catch (IOException e) {
		log.error(e);
	}
}
	
}
